package cn.lxh.template;

import cn.lxh.pojo.bo.WxMessageBo;
import cn.lxh.properties.WxMessageProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @author lxh Create Time: 2024/1/16 18:07
 * 微信消息订阅工具类
 */
@Slf4j
public class WeChatMessageTemplate {

    private WxMessageProperties wxMessageProperties;

    private WeChatTemplate weChatTemplate;

    private RestTemplate restTemplate;

    public WeChatMessageTemplate(WxMessageProperties wxMessageProperties, WeChatTemplate weChatTemplate, RestTemplate restTemplate) {
        this.wxMessageProperties = wxMessageProperties;
        this.weChatTemplate = weChatTemplate;
        this.restTemplate = restTemplate;
    }

    // 推送订阅消息
    public void pushSubscriptionMessages(WxMessageBo wxMessageBo) {
        // 拼接请求地址url
        String url = String.format(wxMessageProperties.getUrl(), weChatTemplate.getAccessToken().getAccess_token());
        // 创建请求头对象
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求头类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        // 构建请求体
        HttpEntity<WxMessageBo> httpEntity = new HttpEntity<>(wxMessageBo, httpHeaders);
        // 发送请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        log.info("发送订阅消息====={}", responseEntity);
    }
}
